package com.lovemanai.listener;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.ResultSet;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
import javax.swing.Timer;

import com.lovemanai.dao.DbDao;


/**
 * 监视在线用户数
 * @author lovemanai
 *
 */
@WebListener
public class OnlineListener implements HttpSessionListener,ServletContextListener {

	//访问时间控制，超过十分钟没有动作则认为用户会话已经过期
	private final int timeout = 10 * 60 * 60;
	
	/**
	 * 用户与服务器之间开始回话是触发此方法
	 */
	@SuppressWarnings("unchecked")
	@Override
	public void sessionCreated(HttpSessionEvent se) {
		/*
		 * 1.获取Session ID
		 * 2.如果是一次新的回话，未登录的用户作为游客处理，并且将在线用户信息放入Map集合中
		 */
		//获取Session
		HttpSession session = se.getSession();
		ServletContext application = session.getServletContext();
		
		//获取Session ID
		String sessionId = session.getId();
		
		if(session.isNew()) {
			String username = (String) session.getAttribute("username");
			username = username == null ? "游客" : username;
			//在线用户信息存储到Map集合中
			Map<String, String> online = (Map<String, String>) application.getAttribute("online");//键值对
			//如果集合为空，创建一个
			if(online == null) {
				online = new HashMap<String, String>();
			}
			//将用户信息存入集合中
			online.put(sessionId, username);
			application.setAttribute("online", online);
		}
	}

	/**
	 * 用户与服务器断开连接是触发此方法
	 */
	@SuppressWarnings("unchecked")
	@Override
	public void sessionDestroyed(HttpSessionEvent se) {
		HttpSession session = se.getSession();
		
		ServletContext application = session.getServletContext();
		String sessionId = session.getId();
		
		Map<String, String> online = (Map<String, String>) application.getAttribute("online");
		
		if(online != null) {
			//如果Map集合不为空，将键值为sessionId的元素移除
			online.remove(sessionId);
		}
		
		application.setAttribute("online", online);
	}

	@Override
	public void contextDestroyed(ServletContextEvent arg0) {
		
		
	}

	@Override
	public void contextInitialized(ServletContextEvent sce) {
		
		//每5秒检查一次
		new Timer(1000 * 5, new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				//数据库连接参数
				String url = "jdbc:mysql://localhost:3306/crazyit";
				String user = "root";
				String password = "root";
				String driver = "com.mysql.jdbc.Driver";
				
				try {
					DbDao dbDao = new DbDao(url, user, password, driver);
					String sql1 = "select * from userinfo";
					ResultSet rs = dbDao.query(sql1);
					while(rs.next()) {
						//超时则将用户信息从数据库中移除
						if(System.currentTimeMillis() - rs.getLong("accesstime") > timeout) {
							String sessionId = rs.getString("sessionid");
							String sql2 = "delete from userinfo where sessionid = ?";
							dbDao.update(sql2, sessionId);
						}
					}
				} catch(Exception ex) {
					 ex.printStackTrace();
				}
			}
		}).start();
		
	}
	

}
